package cn.zlp.basic.controller;

import cn.zlp.basic.util.AjaxResult;
import cn.zlp.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传
 * 下载 = 不需要
 * 查看 = 路径 = http://ip:8888/组名/......
 * 删除
 * 更新 = 删除 + 上传
 */

@RestController
@RequestMapping("/fastDfs")
@Api(tags = "fastDfs文件处理接口",description = "文件上传和删除")
public class FastDfsController {

    //@RequestPart对复杂表单项的处理，默认name="file",与上传文件的name属性值一致
    @PostMapping
    @ApiOperation(value = "上传文件接口",notes = "需要传入上传的文件")
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            // System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            // System.out.println(extName);
            // 工具类返回的完整路径：/goup1/xxxxx/yyyy
            String filePath =  FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败!"+e.getMessage());
        }
    }
    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     */
    @DeleteMapping
    @ApiOperation(value = "删除文件接口",notes = "需要传入文件的路径")
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            //System.out.println(groupName);//获取组名
            //System.out.println(remotePath);//远程路径
            FastDfsUtil.delete(groupName, remotePath);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败!"+e.getMessage());
        }
    }
}